package cn.wsn2018.tools.dao.impl;

import cn.wsn2018.tools.dao.ProtocolDesignDao;
import cn.wsn2018.tools.model.*;
import cn.wsn2018.tools.model.Config.ProtocolConfig;
import cn.wsn2018.tools.model.Design.ProtocolDesign;
import cn.wsn2018.tools.model.Exception;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.logging.Logger;

/**
 * Created by NZX on 2018/12/13.
 */
@Repository("protocolDesignDao")
public class ProtocolDesignDaoImpl implements ProtocolDesignDao{
    private Logger logger = Logger.getLogger(ProtocolDesignDaoImpl.class.getName());

    @Autowired
    private MongoTemplate mongoTemplate;

    @Override
    public String saveProtocolDesign(ProtocolDesign protocolDesign) {
        JSONObject result = JSONObject.fromObject(mongoTemplate.insert(protocolDesign,"protocolDesign"));
        String id = result.optString("id");
        if(id!=null&&!"".equals(id)) {
            return id;
        }
        else {
            return null;
        }
    }

    @Override
    public ProtocolDesign getProtocolDesign(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        ProtocolDesign protocolDesign = mongoTemplate.findOne(query,ProtocolDesign.class,"protocolDesign");
        return protocolDesign;
    }

    @Override
    public List<ProtocolDesign> getProtocolDesigns(String username,String pageNum,String pageSize) {
        Query query = new Query();
        query.addCriteria(Criteria.where("username").is(username));
        query.with(new Sort(Sort.Direction.DESC,"createTime"));
        int num = Integer.parseInt(pageNum);
        int size = Integer.parseInt(pageSize);
        query.skip((num-1)*size).limit(size);
        List<ProtocolDesign> protocolDesigns = mongoTemplate.find(query,ProtocolDesign.class,"protocolDesign");
        return protocolDesigns;
    }

    @Override
    public boolean updateProtocolDesign(ProtocolDesign design) {

        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(design.getId()));
        Update update = new Update();

        //查找配置
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("designId").is(design.getId()));
        ProtocolConfig protocolConfig = mongoTemplate.findOne(query1, ProtocolConfig.class, "protocolConfig");
        if(protocolConfig==null){
            //配置为空
            //配置更新对象
            Update update1 = new Update();

            update.set("protocolName",design.getProtocolName())
                    .set("designName",design.getDesignName())
                    .set("createTime",design.getCreateTime());
            if(design.getOther()!=null){
                update.set("other",design.getOther());
            }

            if(design.getAuth()!=null){
                //有认证
                update.set("auth",design.getAuth());
            }else{
                update.set("auth",null);
                update1.set("authType","");
            }

            if(design.getEncrypt()!=null){
                //有加密
                update.set("encrypt",design.getEncrypt());
            }else{
                //无加密 协议设计和配置直接都置为null
                update.set("encrypt",null);
                update1.set("encrypt",null);
            }

            if(design.getException()!=null){
                //有异常检测
                update.set("exception",design.getException());
            }else{
                update.set("exception",null);
                update1.set("exception",null);
            }

            if(design.getVirus()!=null){
                //有病毒检测
                update.set("virus",design.getVirus());
            }else{
                update.set("virus",null);
                update1.set("virus",null);
            }

            if(design.getResend()!=null){
                //有重传
                update.set("resend",design.getResend());
            }else{
                update.set("resend",null);
                update1.set("resend",null);
            }

            if(design.getIntegrity()!=null){
                //有完整性
                update.set("integrity",design.getIntegrity());
            }else{
                update.set("integrity",null);
                update1.set("integrity",null);
            }
            if(design.getzTree()!=null){
                update.set("zTree",design.getzTree());
            }else{
                update.set("zTree",null);
            }

            JSONObject result = JSONObject.fromObject(mongoTemplate.updateFirst(query,update,"protocolDesign"));
            String count = result.optString("modifiedCount");

            if(count!=null&&"1".equals(count)){
                return true;
            }else {
                return false;
            }

        }else{
            //配置不为空
            //配置更新对象
            Update update1 = new Update();

            update.set("protocolName",design.getProtocolName())
                    .set("designName",design.getDesignName())
                    .set("createTime",design.getCreateTime());
            if(design.getOther()!=null){
                update.set("other",design.getOther());
            }

            if(design.getAuth()!=null){
                //有认证
                update.set("auth",design.getAuth());
                if("".equals(protocolConfig.getAuthType().trim())){
                    update1.set("authType","1-RTT");
                }else{
                    update1.set("authType",protocolConfig.getAuthType().trim());
                }
            }else{
                update.set("auth",null);
                update1.set("authType","");
            }

            if(design.getEncrypt()!=null){
                //有加密
                update.set("encrypt",design.getEncrypt());
                if(protocolConfig.getEncrypt()==null || protocolConfig.getEncrypt().getAlgorithm()==null){
                    //之前配置没有
                    Encrypt encrypt = new Encrypt();
                    encrypt.setAlgorithm("3DES算法");
                    encrypt.setMode("ECB");
                    encrypt.setOutput("base64");
                    encrypt.setRange("0");
                    update1.set("encrypt",encrypt);
                }else{
                    //之前配置有
                    update1.set("encrypt",protocolConfig.getEncrypt());
                }
            }else{
                //无加密 协议设计和配置直接都置为null
                update.set("encrypt",null);
                update1.set("encrypt",null);
            }

            if(design.getException()!=null){
                //有异常检测
                update.set("exception",design.getException());
                if(protocolConfig.getException()==null || protocolConfig.getException().getMethod()==null){
                    //之前配置没有
                    Exception exception = new Exception();
                    exception.setMethod("字段长度溢出");
                    update1.set("exception",exception);
                }else{
                    //之前配置有
                    update1.set("exception",protocolConfig.getException());
                }
            }else{
                update.set("exception",null);
                update1.set("exception",null);
            }

            if(design.getVirus()!=null){
                //有病毒检测
                update.set("virus",design.getVirus());
                if(protocolConfig.getVirus()==null || protocolConfig.getVirus().getMethod()==null){
                    //之前配置没有
                    Virus virus = new Virus();
                    virus.setMethod("文件扫描");
                    update1.set("virus",virus);
                }else{
                    //之前配置有
                    update1.set("virus",protocolConfig.getVirus());
                }
            }else{
                update.set("virus",null);
                update1.set("virus",null);
            }

            if(design.getResend()!=null){
                //有重传
                update.set("resend",design.getResend());
                if(protocolConfig.getResend()==null || protocolConfig.getResend().getTime()==null){
                    //之前配置没有
                    Resend resend = new Resend();
                    resend.setCount("1");
                    resend.setQueue("3");
                    resend.setTime("10.000");
                    update1.set("resend",resend);
                }else{
                    //之前配置有
                    update1.set("resend",protocolConfig.getResend());
                }
            }else{
                update.set("resend",null);
                update1.set("resend",null);
            }

            if(design.getIntegrity()!=null){
                //有完整性
                update.set("integrity",design.getIntegrity());
                if(protocolConfig.getIntegrity()==null || protocolConfig.getIntegrity().getAlgorithm()==null){
                    //之前配置没有
                    Integrity integrity = new Integrity();
                    integrity.setAlgorithm("MD5");
                    update1.set("integrity",integrity);
                }else{
                    //之前配置有
                    update1.set("integrity",protocolConfig.getIntegrity());
                }
            }else{
                update.set("integrity",null);
                update1.set("integrity",null);
            }

            if(design.getzTree()!=null){
                update.set("zTree",design.getzTree());
            }else{
                update.set("zTree",null);
            }


            JSONObject result = JSONObject.fromObject(mongoTemplate.updateFirst(query,update,"protocolDesign"));
            JSONObject result1 = JSONObject.fromObject(mongoTemplate.updateFirst(query1,update1,"protocolConfig"));
            String count = result.optString("modifiedCount");

            if(count!=null&&"1".equals(count)){
                return true;
            }else {
                return false;
            }
        }

    }

    @Override
    public boolean deleteProtocolDesign(String id) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(id));
        JSONObject result = JSONObject.fromObject(mongoTemplate.remove(query,"protocolDesign"));
        String count = result.optString("deletedCount");

        /*由于协议设计和配置一对一，因此删除协议设计也要一起删除协议配置-song*/
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("designId").is(id));
        JSONObject result1 = JSONObject.fromObject(mongoTemplate.remove(query1, "protocolConfig"));
        String count1 = result1.optString("deletedCount");


        if((count!=null&&"1".equals(count))){
            return true;
        }else {
            return false;
        }
    }

    @Override
    public int deleteProtocolDesigns(List<String> idList) {
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").in(idList));
        JSONObject result = JSONObject.fromObject(mongoTemplate.remove(query,"protocolDesign"));
        String count = result.optString("deletedCount");

        /*批量删除协议设计时，配置也会批量删除*/
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("designId").in(idList));
        JSONObject result1 = JSONObject.fromObject(mongoTemplate.remove(query1, "protocolConfig"));
        String count1 = result1.optString("deletedCount");



        return Integer.parseInt(count);


    }
}
